package java_enum;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;

public class TestEnumTypeAdapter2 {
    Type type;
    int x;
    double y;

    public TestEnumTypeAdapter2(Type type, int x, double y) {
        this.type = type;
        this.x = x;
        this.y = y;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (!(obj instanceof TestEnumTypeAdapter2)) {
            return false;
        }

        TestEnumTypeAdapter2 des = TestEnumTypeAdapter2.class.cast(obj);
        if (des.type == type && des.x == x && isEqual(des.y, y)) {
            return true;
        }

        return false;
    }

    boolean isEqual(double a, double b) {
        if (Double.isNaN(a) || Double.isNaN(b) || Double.isInfinite(a) || Double.isInfinite(b)) {
            return false;
        }
        return (a - b) < 0.001d;
    }


    public static <T> T fromJson(Gson gson, String s, Class<T> c) {
        T bean = null;
        if (c != null && s != null) {
            try {
                bean = gson.fromJson(s, c);
            } catch (JsonSyntaxException e) {
                e.printStackTrace();
                try {
                    /**
                     * 如果有默认的无参构造函数，则返回值不为空
                     */
                    bean = c.newInstance();
                } catch (InstantiationException e1) {
                    e1.printStackTrace();
                } catch (IllegalAccessException e1) {
                    e1.printStackTrace();
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        return bean;
    }

    static Gson gson = new Gson();
    public static void main(String[] args) {
        long t1 = System.currentTimeMillis();
        int loop = Type.LOOP;
        int count = 0;
        for (int i = 0; i < loop; i++) {
            for (Type type : Type.values()) {
                TestEnumTypeAdapter2 adapter = new TestEnumTypeAdapter2(type, i, 0);
                String json = gson.toJson(adapter);
                TestEnumTypeAdapter2 tmp = fromJson(gson, json, TestEnumTypeAdapter2.class);
                if (tmp.equals(adapter)) {
                    count += 1;
                }
            }
        }
        long delta = System.currentTimeMillis() - t1;
        System.out.println("count:" + count);
        System.out.println("deltaTime:" + delta);

    }

}
